﻿using ZeldoEngine;
using System.Drawing;
using ZeldoEngineObjects;

namespace MapEditor.Windows.EditorWindows
{
    /// <summary>
    /// Méthodes associées a la manipulation des tuiles sur la section droite de l'editeur
    /// </summary>
    public partial class MainWindowsActions
    {
        public void DebuterSelection(int x, int y)
        {
            if (AppParams.GetIns().MapLoaded)
            {
                this._selecting = true;
                var tilePerLine = EngineConsts.CHIPSET_WIDTH / EngineConsts.TILE_SIZE;
                AppParams.GetIns().StartSelectedTile = ((y / EngineConsts.TILE_SIZE) * tilePerLine) + (x / EngineConsts.TILE_SIZE);

                this.SelectionnerTuile(x, y);
            }
        }

        public void TerminerSelection(int x, int y)
        {
            if (AppParams.GetIns().MapLoaded)
            {
                this.SelectionnerTuile(x, y);
                this._selecting = false;
            }
        }

        public void SelectionnerTuile(int x, int y)
        {
            if (AppParams.GetIns().MapLoaded && _selecting)
            {
                var tilePerLine = EngineConsts.CHIPSET_WIDTH / EngineConsts.TILE_SIZE;
                AppParams.GetIns().EndSelectedTile = ((y / EngineConsts.TILE_SIZE) * tilePerLine) + (x / EngineConsts.TILE_SIZE);

                if (AppParams.GetIns().EndSelectedTile < AppParams.GetIns().StartSelectedTile)
                {
                    var end = AppParams.GetIns().EndSelectedTile;
                    AppParams.GetIns().EndSelectedTile = AppParams.GetIns().StartSelectedTile;
                    AppParams.GetIns().StartSelectedTile = end;
                }

                var startLine = AppParams.GetIns().StartSelectedTile / tilePerLine;
                var endLine = AppParams.GetIns().EndSelectedTile / tilePerLine;

                var point = new Point();
                point.X = (AppParams.GetIns().StartSelectedTile - (tilePerLine * startLine)) * EngineConsts.TILE_SIZE;
                point.Y = startLine * EngineConsts.TILE_SIZE;

                var size = new Size();
                size.Width = ((AppParams.GetIns().EndSelectedTile - (tilePerLine * endLine)) * EngineConsts.TILE_SIZE + EngineConsts.TILE_SIZE) - point.X;
                size.Height = (endLine * EngineConsts.TILE_SIZE + EngineConsts.TILE_SIZE) - point.Y;

                AppParams.GetIns().Selection = new Rectangle(point, size);

                this.windows.ActualiserTileset();
            }
        }
    }
}
